import Vue from 'vue'
import axios from './request'
import qs from 'qs'
import CryptoJS from 'crypto-js'
import { getToken } from '@/utils/util.js'
const BASE_API = process.env.VUE_APP_API_BASE_URL
const CODE = process.env.VUE_APP_API_CODE 
const SIGN = process.env.VUE_APP_API_SIGN
let engine

export default class {
  // "OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT"
  
  _request2({url, method, param, baseUrl}) {
    // param.pssid = getToken('pssid');
    baseUrl = baseUrl ? baseUrl : BASE_API;
    return new Promise(function(resolve, reject) {
      if (!url || !method) {
        reject('param error')
        return
      }
      let params
      const paramstr = JSON.stringify(param)
      // get请求和post请求参数拼接方法不一样
      if (method == 'GET') {
        params = {
          code: CODE,
          param: param ? encodeURIComponent(engine._encrypt(paramstr, CODE, SIGN)) : undefined
        }
        if (params) {
          let value
          for (const key in params) {
            const item = params[key]
            if (item != null && item !== undefined) {
              if (value) {
                value += '&' + key + '=' + item
              } else {
                value = '?' + key + '=' + item
              }
            }
          }
          if (value) {
            url = url + value
          }
        }
      } else {
        params = param
      }

      const oDownlaod = param && param.downLoad ? 'blob' : '' // param.downLoad为true下载二进制流文件
      const time = oDownlaod === 'blob' ? '60000' : '20000' // 下载PDF超时时间延长至60S
      const option = {
        url: url,
        method: method,
        data: params,
        baseURL: baseUrl, // 默认baseUrl,如果有配置则用配置的
      }
      axios(option).then(function(res) {
        resolve(res)
      }).catch(function(reason) {
        reject(reason)
      })
    })
  }
  // 专门针对文件上传
  _upload({url, method, param, file, baseUrl}) {
    baseUrl = baseUrl ? baseUrl : BASE_API;
    param.pssid = getToken('pssid');
   return new Promise(function(resolve, reject) {
     if (!url || !method) {
       reject('param error')
       return
     }

     let paramdata = new FormData()
     paramdata.append('code', CODE)
     paramdata.append('type', param.type)
     paramdata.append('file', file)
     const option = {
       url: url,
       method: method,
       data: paramdata,
       baseURL: baseUrl // 默认baseUrl,如果有配置则用配置的
     }
     axios(option).then(function(res) {
       resolve(res)
     }).catch(function(reason) {
       reject(reason)
       console.log(reason)
     })
   })
  }
  
  _encrypt(param, code, sign) {  
    let key = CryptoJS.enc.Utf8.parse(sign.toString());
    let encrypted = CryptoJS.AES.encrypt(param, key, {
        iv:  CryptoJS.enc.Utf8.parse(sign.substring(0,16)),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.toString()
  }
  constructor() {
    engine = this
  }
}
